
<template>
  <div class="start-video-word-box">
    <div id="play_window" class="video">介里是视频</div>
    <div class="cleft">
      <pcd
        :title="
          state.taskItem.taskName + '(' + state.taskItem.deviceCount + ')'
        "
      >
        <div class="modelist">
          <el-progress
            :percentage="state.taskItem.complRate"
            color="#2263BF"
            :format="format"
          />
        </div>
        <el-timeline class="gzxc">
          <el-timeline-item
            v-for="(item, index) in state.routeList"
            :key="index"
            :icon="item.state != 0 ? 'Check' : ''"
            :type="item.state != 0 ? 'primary' : ''"
            :size="item.state != 0 ? 'large' : 'normal'"
            :class="
              state.routeItem.routeId == item.routeId
                ? 'itemSty_pick'
                : 'itemSty'
            "
          >
            <div>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <div class="itemNr">
                  <div>{{ item.deviceName }}</div>
                </div>
                <div
                  class="wtslSty"
                  style="margin-right: 14px"
                  v-if="item.eventCnt != 0"
                >
                  {{ item.eventCnt }}
                </div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
        <div class="xjBtn">
          <el-button
            style="
              height: 34px;
              background: linear-gradient(90deg, #dce8fb 0%, #e8f1ff 100%);
              border-radius: 6px;
              color: #2263bf;
              width: 100%;
              margin-left: 12px;
              background: #e0edff;
            "
            @click="showd"
            >查看巡检记录</el-button
          >
          <el-button
            style="margin-top: 6px; width: 100%; background: #2263bf"
            type="primary"
            @click="navigateTo('/WorkPatrol')"
            >退出巡查</el-button
          >
        </div>
      </pcd>
    </div>
    <div class="ccenter">
      <div class="spczSty">
        <div>
          <el-button @click="prev"
            ><el-icon> <ArrowLeft /> </el-icon>上一个</el-button
          >
          <el-button @click="next"
            >下一个<el-icon> <ArrowRight /> </el-icon
          ></el-button>
        </div>
        <div>
          <el-popover :visible="state.visible" placement="top" :width="226">
            <template #reference>
              <el-button
                :type="state.visible ? 'primary' : ''"
                @click="state.visible = !state.visible"
                >云台控制</el-button
              >
            </template>
            <ptz :did="state.routeItem.deviceId" />
          </el-popover>
        </div>
      </div>
    </div>

    <div class="cright">
      <xcsjjl :list="state.eventList" />
      <pcd title="">
        <div class="gzxc1">
          <!-- <div style="display: felx">
            <span>业务类型</span>
            <el-select
              v-model="state.sjsb.busiType"
              placeholder="请选择"
              style="width: 190px; margin-left: 10px"
            >
              <el-option
                v-for="(item, inx) in state.eventDeptList"
                :key="inx"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
          </div> -->
          <div style="display: felx; margin-top: 5px">
            <span>事件类型</span>
            <el-select
              v-model="state.sjsb.eventCode"
              placeholder="请选择"
              style="width: 190px; margin-left: 10px"
              filterable
            >
              <el-option
                v-for="(item, inx) in state.eventTypeList"
                :key="inx"
                :label="item.key"
                :value="item.value"
              />
            </el-select>
          </div>
          <div style="display: felx; margin-top: 5px">
            <span>紧急程度</span>
            <el-select
              v-model="state.sjsb.eventClass"
              placeholder="请选择"
              style="width: 190px; margin-left: 10px"
            >
              <el-option
                v-for="(item, inx) in state.eventJList"
                :key="inx"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
          </div>
          <div class="tpSty1" @click="catpic" title="单击截图">
            <img
              style="width: 100%; height: 100%"
              :src="state.image"
              v-if="state.image != ''"
            />
            <div
              style="
                width: 32px;
                height: 32px;
                background: #6e8dfb;
                border-radius: 4px;
                display: flex;
                justify-content: center;
                align-items: center;
              "
              v-if="state.image == ''"
            >
              <el-icon :size="20">
                <Crop style="color: #fff" />
              </el-icon>
            </div>
          </div>
          <el-input
            v-model="state.sjsb.description"
            style="width: 100%; margin-top: 5px"
            type="textarea"
            placeholder="请输入问题记录"
          />
          <el-button
            style="
              width: 100px;
              margin-top: 5px;
              margin-left: 155px;
              background: #2263bf;
            "
            type="primary"
            @click="submit"
            >提交</el-button
          >
        </div>
      </pcd>
      <xjjld :show="state.dialog" :item="state.taskItem" />
    </div>
  </div>
</template>

<script setup>
import {
  getcameraurl,
  uploadpic,
  reportevent,
  getparamdict,
  bydeviceid,
  updtaskroutestate,
} from "@/api/videoplan.js";
import { getEventTypeList } from "@/api/event.js";
import { ElMessage } from "element-plus";
import xcsjjl from "./xcsjjl.vue";
import xjjld from "./xjjld.vue";
import { useMyStore } from "@/pinia/store";
import pcd from "@/components/videoplan/pcd.vue";
import ptz from "@/components/videoplan/ptz.vue";
import { percentNumber } from "@/utils/index.ts";

const format = (percentage) => " 进度：" + `${percentNumber(percentage)}`;

const state = reactive({
  packZt: true,
  packZt1: true,
  dialog: false,
  taskItem: {},
  routeList: [],
  routeItem: {},

  eventTypeList: [],
  eventJList: [],
  // eventDeptList: [],//业务类型

  visible: false,
  eventList: [],
  myPlugin: null,
  curIndex: 0, //视频索引
  start: null, //开始时间

  sjsb: {
    deviceId: "",
    taskId: "",
    // busiType: "",
    eventCode: "",
    eventClass: "",
    eventPic: "",
    description: "",
  },
  image: "",
});

const showd = () => {
  state.dialog = false;
  setTimeout(() => {
    state.dialog = true;
  }, 300);
};

const chrstate = async (item) => {
  //检测是否可以更新状态
  if (item.routeId && state.start !== null) {
    let now = new Date().getTime();
    let sub = now - state.start;
    //时间超过设定分钟，则可以更新状态
    if (sub >= state.taskItem.duration * 1000) {
      let { data } = await updtaskroutestate({
        deviceId: item.deviceId,
        taskId: state.taskItem.taskId,
        state: "1",
      });
      state.taskItem.complRate = data.complRate;
      state.routeList = [...data.routeInfoList];
    }
  }
  //设置新的开始时间
  state.start = new Date().getTime();
};
const prev = () => {
  let inx = state.routeList.findIndex(
    (item) => item.deviceId == state.routeItem.deviceId
  );
  inx--;
  if (inx == -1) {
    inx = state.routeList.length - 1;
  }
  chrstate(state.routeItem);
  state.routeItem = state.routeList[inx];
  getEventList();
  play();
};
const next = () => {
  let inx = state.routeList.findIndex(
    (item) => item.deviceId == state.routeItem.deviceId
  );
  inx++;
  if (inx == state.routeList.length) {
    inx = 0;
  }
  chrstate(state.routeItem);
  state.routeItem = state.routeList[inx];
  getEventList();
  play();
};
const getEventList = async () => {
  try {
    let { data } = await bydeviceid({
      deviceId: state.routeItem.deviceId,
    });
    state.eventList = [...(data.eventInfoList || [])];
  } catch (e) {
    console.error(e);
  }
};

const getTypeList = async () => {
  try {
    let res = await getEventTypeList();
    state.eventTypeList = res.data.map((item) => {
      return (item = {
        ...item,
        key: item.eventDefineDisplay,
        value: item.eventDefine,
      });
    });
    console.log("state.eventTypeList", state.eventTypeList);
    let { data } = await getparamdict();
    state.eventJList = [...(data.event_class || [])];
    // state.eventTypeList = [...(data.event_type || [])];
    // state.eventDeptList = [...(data.business_type || [])];
  } catch (e) {
    console.error(e);
  }
};
const submit = async () => {
  // if (state.sjsb.busiType == "") {
  //   ElMessage.error("请选择业务类型");
  //   return;
  // }
  if (state.sjsb.eventCode == "") {
    ElMessage.error("请选择事件类型");
    return;
  }
  if (state.sjsb.eventClass == "") {
    ElMessage.error("请选择紧急程度");
    return;
  }
  if (state.sjsb.eventPic == "") {
    ElMessage.error("请截取图片");
    return;
  }
  if (state.sjsb.description == "") {
    ElMessage.error("请输入问题");
    return;
  }
  state.sjsb.deviceId = state.routeItem.deviceId;
  state.sjsb.taskId = state.taskItem.taskId;
  let { data } = await reportevent(state.sjsb);
  state.eventList = [...(data.eventInfoList || [])];
  state.sjsb = {
    deviceId: "",
    taskId: "",
    // busiType: "",
    eventCode: "",
    eventClass: "",
    eventPic: "",
    description: "",
  };
  state.image = "";
  ElMessage.success("事件上报成功");
  getEventList();
};
const catpic = async () => {
  let fileName = "img";
  let fileType = "JPEG";
  if (state.myPlugin != null) {
    state.myPlugin.JS_CapturePicture(
      state.curIndex,
      fileName,
      fileType,
      async (imageData) => {
        state.image = imageData;
        //上传文件
        let formdata = new FormData();
        formdata.append("file", base64ToImage(imageData));
        let config = { headers: { "Content-Type": "multipart/form-data" } };
        let { data } = await uploadpic(formdata);
        state.sjsb.eventPic = data.picPath || "";
      }
    );
  }
};
//base64转文件
const base64ToImage = (dataurl) => {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], "picfile.jpg", { type: mime });
};
//左侧列表选择返回
const play = async () => {
  //根据选择 获取监控点播放地址，尝试播放
  try {
    let { data } = await getcameraurl({
      deviceIds: [state.routeItem.deviceId],
    });
    let urls = data.cameraUrls || [];
    // let urls = [
    //   {
    //     cameraId: "1766027258713215018",
    //     cameraUrl: "wss://zxz.linghang.tech:18087/openUrl/xzkXFn2",
    //   },
    // ];
    if (urls.length > 0) {
      let obj = { playURL: urls[0].cameraUrl, mode: 1 };
      state.myPlugin.JS_Stop(state.curIndex);
      state.myPlugin
        .JS_Play(urls[0].cameraUrl, obj, state.curIndex)
        .then(() => {
          state.start = new Date().getTime();
          state.myPlugin.JS_EnableZoom(0);
        });
    }
  } catch (e) {
    console.error(e);
  }
};
const initPlayer = () => {
  state.myPlugin = new JSPlugin({
    szId: "play_window", //需要英文字母开头，唯一性，必填
    szBasePath: "/js/", // 必填,与h5player.min.js的引用目录一致
    bSupporDoubleClickFull: true, //是否支持双击全屏，默认true
    // 分屏播放，默认最大分屏4*4
    iMaxSplit: 9,
    iCurrentSplit: 1,
  });

  state.myPlugin.JS_SetWindowControlCallback({
    windowEventSelect: function (index) {
      //插件选中窗口回调
      state.curIndex = index;
    },
    pluginErrorHandler: function (iWndIndex, iErrorCode, oError) {
      //插件错误回调
      console.error(`window-${iWndIndex}, errorCode: ${iErrorCode}`, oError);
      ElMessage.error(`播放失败, 错误码: ${iErrorCode}`);
      //回复变量
      state.curIndex = 0; //设置播放窗口号=0
      state.start = null; //设置播放开始时间=null，也就是没有开始
    },
  });
};
const destoryPlayer = () => {
  if (state.myPlugin) {
    state.myPlugin.JS_StopRealPlayAll();
    state.myPlugin.JS_DestroyWorker();
    state.myPlugin = null;
  }
};
onMounted(() => {
  //初始化播放组件
  initPlayer();

  //获取传递参数
  let store = useMyStore();
  // let params = useState("routeitem").value;
  state.taskItem = store.params.taskItem;
  state.routeList = store.params.routeList;
  console.log("初始化的时候state.taskItem", state.taskItem);
  console.log("store.params.routeList", store.params.routeList);
  //查找第一个巡查
  for (let item of state.routeList) {
    if (item.state == 0) {
      state.routeItem = item;
      getEventList();
      play();
      break;
    }
  }
  //获取列表
  getTypeList();
});

//注销时 销毁组件
onBeforeUnmount(() => {
  state.visible = false;
  destoryPlayer();
});
</script>

<style lang="scss">
.start-video-word-box {
  width: 100%;
  height: 100%;
  position: relative;
}
.sub-wnd {
  border: none !important;
  background-color: #e9effb !important;
}
</style>
<style scoped lang="scss">
.video {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  background-color: #f2f2f2;
}

.cleft {
  position: absolute;
  left: 0;
  top: 0;
  width: auto;
  height: auto;
  display: flex;
  flex-direction: column;
}
.tlcenter {
  position: absolute;
  left: 380px;
  top: 20px;
}
.trcenter {
  position: absolute;
  right: 380px;
  top: 20px;
}
.ccenter {
  position: absolute;
  left: 50%;
  bottom: 0;
  width: 834px;
  height: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  transform: translateX(-50%);
}
.cright {
  position: absolute;
  right: 0;
  top: 0;
  width: auto;
  height: auto;
  display: flex;
  flex-direction: column;
}
.bc {
  height: 0;
  width: 0;
  position: relative;
}
.btn {
  position: absolute;
  top: 30px;
  left: -150px;
  color: #ffffff;
  background: #6e8dfb;
  border-radius: 8px;
}
.pos {
  position: absolute;
  left: 40%;
  top: 10px;
  width: 200px;
  opacity: 0.8;
  z-index: 9999;
}
.spczSty {
  width: 900px;
  background: rgba(41, 53, 85, 0.3);
  border-radius: 30px;
  margin-bottom: 20px;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.modelist {
  border-radius: 6px;
  margin: 20px 0 0;
  margin: 0 16px;
}
.modes {
  width: 50%;
  height: 36px;
  cursor: pointer;
  /* border-radius: 6px; */
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center;
}
.modetext {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 16px;
  color: #000000;
  line-height: 22px;
}

.activemodetext {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 16px;
  color: #fefefe;
  line-height: 22px;
}

.active {
  background: #6e8dfb;
}
/* 1.过渡动画 */
@keyframes axisX {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
.v-enter-active {
  animation: axisX 0.5s;
}
.gzxc {
  margin-top: 20px;
  padding-left: 0px;
  height: 580px;
  overflow: auto;
  .el-timeline-item {
    height: 46px;
    line-height: 46px;
    padding-bottom: 0px;
  }
}
:deep(.el-timeline-item__tail) {
  top: 17px;
  left: 20px;
}
:deep(.el-timeline-item__node--normal) {
  top: 15px;
  left: 15px;
}
:deep(.el-timeline-item__node--large) {
  top: 15px;
  left: 15px;
}
:deep(.el-timeline-item__wrapper) {
  padding-left: 35px;
}
.itemSty {
  font-size: 14px;
  cursor: pointer;
}
.itemSty_pick {
  font-size: 14px;
  background: rgba(142, 191, 255, 0.22);
  color: #2263bf;
  cursor: pointer;
  .itemNr {
    color: #2263bf;
  }
}

.itemNr {
  display: flex;
  align-items: center;
}
::-webkit-scrollbar-thumb {
  background: #d3e3fd;
  border-radius: 4px;
}
::-webkit-scrollbar {
  width: 8px;
  height: 100px;
}
:deep(.el-progress-bar__outer) {
  background: rgba(110, 141, 251, 0.51);
  box-shadow: inset 2px 1px 4px 0px #b5bde7;
}
.xjBtn {
  padding: 16px 20px 16px 0;
  margin: 0 20px;
  border-top: #ccddf7 1px solid;
  box-shadow: 0px 0px 1px 0px #ffffff;
}
.wtslSty {
  width: 20px;
  height: 20px;
  background: #ff7575;
  border-radius: 50%;
  text-align: center;
  line-height: 20px;
  color: #ffffff;
  font-size: 12px;
}

.gzxc1 {
  background-color: #fff;
  margin: 10px 0;
  border-radius: 8px;
  padding: 10px 10px;
}
.tpSty1 {
  margin-top: 5px;
  width: 100%;
  height: 142px;
  background: #f0f2f7;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
</style>

<style lang="scss">
.el-progress__text {
  color: #2263bf !important;
}
</style>
